package com.yc.biz.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.yc.bean.Cartinfo;
import com.yc.biz.CartinfoBiz;
import com.yc.dao.DBHelper;

public class CartinfoBizImpl implements CartinfoBiz {

	DBHelper db=new DBHelper();
	
	@Override//添加商品到购物车
	public int addCart(int uid, int gid) {
		//避免重复添加相同的商品   添加之前先进性判断  此商品购物车中是否已经存在
		String sql1="select * from cartinfo where gid="+gid;
		List<Map<String,String>> list=db.findAll(sql1, null);
		String sql="";
		if(list.isEmpty()){
			sql="insert into cartinfo value(null,"+uid+","+gid+",1)";
			
		}else{
			sql="update cartinfo set num=num+"+1+" where uid="+uid+" and gid="+gid;
		}
		return db.doUpdate(sql, null);
	}

	@Override//查询购物车数量
	public int findCartNum(int uid) {
		String sql="select * from cartinfo where uid="+uid;
		return db.findAll(sql, null).size();
	}

	@Override//查询购物车的所有信息
	public List<Cartinfo> findAll(int uid) {
		String sql="select cid,cartinfo.num,good.*,cartinfo.num*price as allprice from cartinfo,good  where good.gid=cartinfo.gid and uid="+uid;
		return db.find(sql, null, Cartinfo.class);
	}

	@Override//更改购物车的数量
	public int updateNum(int uid, int gid, int num) {
		String sql="update cartinfo set num="+num+" where uid="+uid+" and gid="+gid;
		return db.doUpdate(sql, null);
	}

	@Override//删除购物车的某件商品
	public int del(int gid,int uid) {
		String sql="delete from cartinfo where uid="+uid+" and gid="+gid;		
		return db.doUpdate(sql, null);
	}

	@Override//计算总数量与总价
	public List<Map<String, String>> countAll(int uid) {
		String sql="select cartinfo.num,cartinfo.num*price as allprice from cartinfo,good  where good.gid=cartinfo.gid and uid="+uid;
		return db.findAll(sql, null);
	}

	@Override//结算页面的页面显示  一次最多提交五个订单
	public List<Map<String, String>> show(int uid, String str) {
		int length=str.split(",").length;//2   15,17
		int arr[]=new int[length];
		System.out.println("长度为："+length+"str="+str);//长度为：2 str=4,6
		List<Object> params=new ArrayList<Object>();
		params.add(uid);
		String sql="";
		String ss="";
		for(int i=0;i<length-1;i++){
			ss+="?,";
		}
		ss+="?";
		sql="select good.*,cid,uid,num,num*price as allprice from good,cartinfo where good.gid=cartinfo.gid and uid=? and cid in("+ss+")";

		for(int i=0;i<length;i++){
			arr[i]=Integer.parseInt(str.split(",")[i]);
			System.out.println(arr[i]);
			params.add(arr[i]);
		}
		System.out.println(db.findAll(sql, params).size());
		return db.findAll(sql, params);
	}



}
